<template>
  <div :class="`low-code-linkage ${visualThemeClassName}`">
    <div class="addAction_line">
      <el-button class="addAction" icon="CirclePlusFilled" @click="addAction">{{ $demoi18n('btn.add') }}</el-button>
    </div>
    <OptionCollapse v-if="initiative.actions.length" :active="activeAction">
      <el-collapse-item v-for="(act, i) in initiative.actions" :key="i" :name="`${i}`">
        <template #title>
          <div class="title_line action_title">
            <span>{{ $demoi18n('word.action') }} {{ i+1 }}</span>
            <el-button
              icon="Delete"
              :link="true"
              type="primary"
              @click="delAction(initiative.actions, i)"
            ></el-button>
          </div>
        </template>
        <div class="trigger_line">
          <div class="trigger">
            <span class="label">{{ $demoi18n('low-code-linkage.triggerAction') }}</span>
            <el-select v-model="act.trigger">
              <el-option
                v-for="item in triggerOps"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>
          <el-button
            class="addAction"
            icon="CirclePlusFilled"
            :link="true"
            type="primary"
            :title="$demoi18n('low-code-linkage.addSteps')"
            @click="addSubAction(act.subActions)"
          ></el-button>
        </div>
        <div v-if="act.trigger === 'onClickDiy'" class="onClickDiy_setting">
          <div class="selector">
            <NodePicker @on-select="handleSelectEl($event, act)" />
            <ValueInputer v-model:value="act.elSelector" :max="300" valueType="Textarea" :rules="getCssPathRules()" />
          </div>
          <div class="preview">
            <span class="label">{{ $demoi18n('low-code-linkage.elementValuePreview') }}</span>
            <ValueInputer v-model:value="act.elSelectorVal" valueType="Input" readonly placeholder="{{xxx.clickedText}}" />
          </div>
        </div>
        <div class="subActions">
          <div v-for="(subAct, i1) in act.subActions" :key="i1" class="subAct_box">
            <div class="title_line">
              <div class="left">
                <span>{{ $demoi18n('low-code-linkage.executionStep') }} {{ i1+1 }}</span>
                <el-select
                  v-model="subAct.actType"
                  :title="$demoi18n('low-code-linkage.actionType')"
                  class="actType"
                  @change="initSubActExecution($event, subAct)"
                >
                  <el-option
                    v-for="item in actTypes"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </div>
              <div class="right">
                <el-button
                  icon="Delete"
                  :link="true"
                  type="primary"
                  @click="delSubAction(act.subActions, i1)"
                ></el-button>
              </div>
            </div>
            <div class="subAct_execution">
              <ValueInputer :key="subAct.id" v-model:value="subAct.execution" required :placeholder="subAct.codeTpl" />
              <el-button
                v-if="subAct.actType === 'api'"
                class="toggleParams"
                icon="Operation"
                :link="true"
                type="primary"
                :title="$demoi18n('low-code-linkage.parametersSetting')"
                @click="toggleParams(subAct)"
              ></el-button>
            </div>

            <!-- 参数设置 -->
            <div v-show="isParamsShow(subAct)" class="params_box">
              <div class="title_line">
                <span class="params_box_title" :title="$demoi18n('low-code-linkage.parametersSetting')">{{ $demoi18n('low-code-linkage.parametersSetting') }}</span>
                <el-button
                  class="addSubParam"
                  icon="CirclePlusFilled"
                  size="small"
                  @click="addSubActParam(subAct.params)"
                >{{ $demoi18n('btn.addParameters') }}</el-button>
              </div>
              <div class="params">
                <div v-for="(param, i2) in subAct.params" :key="i2" class="params_item">
                  <span class="index">{{ i2+1 }}</span>
                  <ValueInputer v-model:value="param.execution" required placeholder="{{api1.params.date=component1.value}}" codeMirrorHeight="40" />
                  <el-button
                    class="del_btn"
                    icon="Delete"
                    :link="true"
                    type="primary"
                    @click="delSubActParam(subAct.params, i2)"
                  ></el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-collapse-item>
    </OptionCollapse>
  </div>
</template>
<script>
import triggers from './low-code-linkage-triggers.js';
import actTypes from './low-code-actTypes.js';
import OptionCollapse from '@/components/common/base-option/option-collapse/option-collapse.vue';
import ValueInputer from '@/components/common/value-inputer/value-inputer.vue';
import NodePicker from '@/components/common/node-picker/node-picker.vue';
import { getCssPathRules } from '@/utils/rules.js';

export default {
  components: { OptionCollapse, ValueInputer, NodePicker },
  props: {
    config: Object,
  },
  data() {
    return {
      activeAction: '0',
      initiative: {
        actions: [
          {
            trigger: 'onClick', // onClick:点击时，onClickDiy:点击时（diy）, onChange:改变时
            subActions: [
              {
                id: 1692173673514, // 防止删除数组，表达式错位不更新用
                actType: 'normal', // normal:普通动作， api:接口查询
                execution: '',
                codeTpl: '{{comp1.params.value=123}}',
                elSelector: '',
                elSelectorVal: '',
                isParamsVisible: true,
                params: [
                  { execution: '{{comp1.params.value=123}}' },
                ],
              },
            ],
          },
        ],
      },
      actTypes,
      curAction: {},
    };
  },
  computed: {
    triggerOps() {
      const compName = this.config.propertyPannelName.replace(`config_${process.env.xvueNameSpace_}`, '');
      let ops = triggers.common;
      if (triggers[compName]) {
        ops = triggers[compName];
      }

      const noDiyComps = ['progress_table'];
      if (!noDiyComps.includes(compName)) {
        ops = [
          ...ops,
          { label: this.$demoi18n('low-code-linkage.whenClickedDiy'), value: 'onClickDiy' },
        ];
      }

      return ops;
    },
  },
  watch: {},
  created() {
    this.initInitiative();
  },
  methods: {
    getCssPathRules,
    initInitiative() {
      if (this.config.initiative) {
        this.initiative = JSON.parse(JSON.stringify(this.config.initiative));
      } else {
        this.initiative = { actions: [] };
      }
      this.initiative.actions.forEach(act => {
        act?.subActions?.forEach(n => {
          if (n?.params?.length) {
            n.isParamsVisible = true;
          }
        });
      });
    },
    addAction() {
      this.initiative.actions.push({
        trigger: this.triggerOps[0].value,
        elSelector: '',
        elSelectorVal: '',
        subActions: [],
      });
    },
    delAction(actions, i) {
      actions.splice(i, 1);
    },
    addSubAction(subActions) {
      subActions.push({
        id: Date.now(), // 防止删除数组，表达式错位不更新用
        actType: 'normal',
        execution: '',
        codeTpl: actTypes[0].codeTpl,
        params: [],
      });
    },
    delSubAction(subActions, i) {
      subActions.splice(i, 1);
    },
    toggleParams(subAct) {
      subAct.isParamsVisible = !subAct.isParamsVisible;
    },
    isParamsShow(subAct) {
      return subAct.actType === 'api' && subAct.isParamsVisible;
    },
    addSubActParam(params) {
      params.push({
        execution: '',
      });
    },
    delSubActParam(params, i) {
      params.splice(i, 1);
    },
    initSubActExecution(value, subAct) {
      const item = actTypes.find(n => n.value === subAct.actType);
      subAct.execution = '';
      subAct.codeTpl = item.codeTpl;
    },

    handleSelectEl({ el, cssPath }, act) {
      act.elSelector = cssPath;
      act.elSelectorVal = el.textContent.trim();
    },

  },
};
</script>
<style lang="less" scoped>
.low-code-linkage{
  .action_title{
    margin-right: 10px;
  }
  .addAction_line{
    display: flex;
    justify-content: flex-end;
    margin-bottom: 10px;
  }
  .title_line{
    display: flex;
    justify-content: space-between;
    width: 100%;
    align-items: center;
  }
  .trigger_line{
    display: flex;
    margin-bottom: 10px;
    .trigger{
      display: flex;
      align-items: center;
      margin-right: 10px;
      .label{
        width: 110px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }
  .onClickDiy_setting{
    .selector{
      display: flex;
      align-items: center;
      .node-picker{
        position: relative;
        left: -5px;
      }
    }
    .preview{
      margin: 10px 0;
      display: flex;
      align-items: center;
    }
    .label{
      width: 100px;
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
    }
    .value-inputer{
      margin-left: 10px;
      width: 180px;
      flex-shrink: 0;
    }
  }
  .subAct_box {
    padding: 10px;
    background-color: #dcdfe6;
    margin-bottom: 10px;
    .title_line{
      margin-top: 10px;
      .left{
        display: flex;
        align-items: center;
      }
      :deep(.actType){
        margin-left: 20px;
        .el-input__wrapper{
          background-color: transparent;
          padding: 0;
          box-shadow: none !important;
          .el-input__inner{
            display: none;
          }
          .el-icon{
            color: #409eff;
            margin-left: 0;
          }
        }
      }
    }
    >.title_line{
      margin-top: 0;
    }
    .subAct_execution{
      margin-top: 10px;
      display: flex;
      align-items: center;
    }
    .params_box{
      margin-top: 10px;
      padding: 0 5px 10px 10px;
      background-color: #e8eaec;
      border: 1px solid #dcdfe6;
      .params_box_title{
        overflow: hidden;
        text-overflow: ellipsis;
        white-space:nowrap;
      }
      .params{
        .params_item{
          display: flex;
          justify-content: space-between;
          margin-top: 10px;
          align-items: center;
          .index{
            width: 20px;
          }
          .del_btn{
            width: 20px;
            margin-left: 4px;
          }
        }
      }
    }
  }
  :deep(.el-collapse-item){
    .el-collapse-item__content{
      padding: 10px !important;
    }
  }
}

.low-code-linkage.visualComponents_theme_dark{
  .trigger_line{
    .trigger{
      .label{
        color: #98cae6;
      }
    }
  }
  .subActions{
    .subAct_box{
      background-color: #1b3952;
      .title_line{
        .left{
          color: #709fba;
          .actType{}
        }
        .right{}
      }
      .subAct_execution{
        .toggleParams{}
      }
    }
    .params_box{
      background-color: #064559;
      border: 1px solid #095871;
      .title_line{
        color: #98cae6;
      }
      .params{
        color: #98cae6;
      }
    }
  }
}

</style>
